// EventBus.js
import { createApp, reactive, provide } from "vue";
import type { InjectionKey } from "vue";
type EventBusRectvie = {
  events: {
    [key: string]: Function[];
  };
};

export type EventBusType = {
  emit: (eventName: string, ...args: any[]) => void;
  on: (eventName: string, callback: Function) => void;
  off: (eventName: string, callback: Function) => void;
};

export const EventBusKey = Symbol() as InjectionKey<EventBusType>;

const eventBus = reactive<EventBusRectvie>({
  events: {},
});

function on(eventName: string, callback: Function) {
  if (!eventBus.events[eventName]) {
    eventBus.events[eventName] = [];
  }
  eventBus.events[eventName].push(callback);
}

function emit(eventName: string, ...args: any[]) {
  if (eventBus.events[eventName]) {
    eventBus.events[eventName].forEach((callback) => {
      callback(...args);
    });
  }
}

function off(eventName: string, callback: Function) {
  if (eventBus.events[eventName]) {
    eventBus.events[eventName] = eventBus.events[eventName].filter(
      (cb) => cb !== callback
    );
  }
}

const EventBus: EventBusType = {
  on,
  emit,
  off,
};

export default EventBus;
